package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDto dto) {
        log.info("异步执行存储搜索记录======>");
        //获取用户行为实体
        ApBehaviorEntry apBehaviorEntry;
        if (dto.getEntryId() != null) {//登陆是用户登录
            apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        } else {//设备登录
            apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        }
        if (apBehaviorEntry == null) {
            log.error("获取用户行为实体失败");
            return;
        }
        //将用户搜索记录存储到mongo中
        //查询关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId())
        .and("keyword").is(dto.getSearchWords())), ApUserSearch.class);

        //存在更新时间，不存在则添加
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
        } else {
            apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(apBehaviorEntry.getId());
            apUserSearch.setKeyword(dto.getSearchWords());
            apUserSearch.setCreatedTime(new Date());
        }
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 查询搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getPageSize() < 1) {
            dto.setPageSize(10);
        }
        //判断用户的登录状态
        ApUser user = AppUserThreadLocalUtils.getUser();
        //获取用户行为实体
        ApBehaviorEntry apBehaviorEntry;
        if (user != null) {
            apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), null);
        } else {//设备登录
            apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        }
        if (apBehaviorEntry == null) {
            log.error("获取用户行为实体失败");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "获取行为实体对象失败");
        }
        //从mongo中查询历史记录
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId")
                .is(apBehaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getPageSize()), ApUserSearch.class);

        //返回响应
        return ResponseResult.okResult(apUserSearchList);

    }

    /**
     * 根据id删除历史记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //参数校验
        if(dto==null||dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据id删除
        ApUserSearch apUserSearch = mongoTemplate.findById(dto.getId(), ApUserSearch.class);
        if(apUserSearch==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"你要删除的历史记录已不存在");
        }
        mongoTemplate.remove(apUserSearch);
        return ResponseResult.okResult();
    }
}
